package com.jpyl.jpMedicalTreatment.view.fragment.common;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.forxindu.kit.box.JavaKit;
import com.forxindu.kit.box.ViewKit;
import com.google.gson.JsonObject;
import com.jpyl.jpMedicalTreatment.R;
import com.jpyl.jpMedicalTreatment.common.MedicalSettings;
import com.jpyl.jpMedicalTreatment.model.CompleteModel;
import com.jpyl.jpMedicalTreatment.model.ErrorMessageModel;
import com.jpyl.jpMedicalTreatment.model.ResponseModel;
import com.jpyl.jpMedicalTreatment.model.RowsModel;
import com.jpyl.jpMedicalTreatment.model.RowsPeripheralModel;
import com.jpyl.jpMedicalTreatment.model.RxSpf_UserModel;
import com.jpyl.jpMedicalTreatment.network.Network;
import com.jpyl.jpMedicalTreatment.network.api.ApiError;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;
import com.jpyl.jpMedicalTreatment.util.StringUtil;
import com.jpyl.jpMedicalTreatment.view.activity.home.DateOfCheckActivity;
import com.jpyl.jpMedicalTreatment.view.activity.home.GeneralAgentActivity;
import com.jpyl.jpMedicalTreatment.view.activity.home.MyDoctorActivity;
import com.jpyl.jpMedicalTreatment.view.activity.home.PatientListActivity;
import com.jpyl.jpMedicalTreatment.view.activity.news.NewDetailsActivity;
import com.jpyl.jpMedicalTreatment.view.activity.self.SecurityCheckActivity;
import com.jpyl.jpMedicalTreatment.view.adapter.HomeAdapter;
import com.jpyl.jpMedicalTreatment.view.fragment.BaseFragment;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * 首页
 * Created by 521546564465 on 2018/11/5.
 */

public class HomeFragment extends BaseFragment {
    @BindView(R.id.rv_refresh_layout)
    RecyclerView rvRefreshLayout;
    @BindView(R.id.mr_refresh_layout)
    MaterialRefreshLayout mrRefreshLayout;
    @BindView(R.id.tv_refreshLayout_Empty)
    TextView tvRefreshLayoutEmpty;

    @BindView(R.id.tv_itemHome_title)
    TextView tv_itemHome_title;

    //医生,代理可见
    @BindView(R.id.linear_doctor)
    LinearLayout linear_doctor;

    // 总代理可见
    @BindView(R.id.linear_generalAgent)
    LinearLayout linear_generalAgent;
    //患者可见
    @BindView(R.id.frame_refrsh_layout)
    FrameLayout frame_refrsh_layout;

    @BindView(R.id.banner_home)
    Banner bannerHome;

    HomeAdapter adapter;

    int flag;//==1患者登陆可见 ==2医生登陆可见
    private List<RowsModel> rowsModelList = new ArrayList<>();
    final RequestApi publicApi = Network.getRequestApi();
    String userID = "";

    public static HomeFragment getInstance(int flag, String userId) {
        Bundle bundle = new Bundle();
        bundle.putInt(MedicalSettings.STRUSERTYPE, flag);
        bundle.putString(MedicalSettings.STRUSERID, userId);
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_fragment_layout;
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        flag = bundle.getInt(MedicalSettings.STRUSERTYPE, -1);
        userID = bundle.getString(MedicalSettings.STRUSERID);
        GetAds();
        switch (flag) {
            case 1://患者登陆可见
                frame_refrsh_layout.setVisibility(View.VISIBLE);
                linear_doctor.setVisibility(View.GONE);
                break;
            case 2://医生登陆可见
                frame_refrsh_layout.setVisibility(View.GONE);
                linear_doctor.setVisibility(View.VISIBLE);
                tv_itemHome_title.setText("患者");
                linear_doctor.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(getActivity(), PatientListActivity.class)
                                .putExtra("flag", "1"));
                    }
                });
                break;
            case 3://代理可见
                frame_refrsh_layout.setVisibility(View.GONE);
                linear_doctor.setVisibility(View.VISIBLE);
                tv_itemHome_title.setText("医生");
                linear_doctor.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(getActivity(), MyDoctorActivity.class).putExtra
                                (MedicalSettings.STRUSERTYPE, MedicalSettings.USERTYPE_AGENT));
                    }
                });

                break;
            case 4://总代理可见
                frame_refrsh_layout.setVisibility(View.GONE);
                linear_doctor.setVisibility(View.VISIBLE);
                tv_itemHome_title.setText("医生");
                linear_generalAgent.setVisibility(View.VISIBLE);
                linear_doctor.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(getActivity(), MyDoctorActivity.class).putExtra
                                (MedicalSettings.STRUSERTYPE, MedicalSettings
                                        .USERTYPE_GENERALAGENT));
                    }
                });
                linear_generalAgent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(getActivity(), GeneralAgentActivity.class));
                    }
                });


                break;
        }
        bannerHome.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                String url = rowsModelList.get(position).getAdsurl();
//                //代码实现跳转
//                Intent intent = new Intent();
//                intent.setAction("android.intent.action.VIEW");
//                Uri content_url = Uri.parse(url);//此处填链接
//                intent.setData(content_url);
//                startActivity(intent);
                startActivity(new Intent(getActivity(), NewDetailsActivity.class).putExtra("url",
                        url).putExtra("name", "广告"));

            }
        });
        patienView();
    }

    /**
     * 患者登录可见
     */
    private void patienView() {
        adapter = new HomeAdapter(getActivity(), getList());
        rvRefreshLayout.setAdapter(adapter);
        rvRefreshLayout.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        mrRefreshLayout.setLoadMore(false);
        mrRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                //刷新
//                page = 1;
//                findNotify(page);
                mrRefreshLayout.finishRefreshing();
                mrRefreshLayout.finishRefresh();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                super.onRefreshLoadMore(materialRefreshLayout);
                //加载更多
//                if (pageNum >= listSize) {
//                    ++page;
//                    findNotify(page);
//                } else {
                materialRefreshLayout.finishRefreshLoadMore();
//                }
            }
        });
        adapter.setItemClickListener(new HomeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                jpylCheckUserCompleteInfo(position);
            }
        });
    }

    /**
     * 查询用户信息是否完成
     * ture 跳转界面，false提示“完善用户信息后查看”
     */
    private void jpylCheckUserCompleteInfo(final int position) {
        final JsonObject body = new JsonObject();
        body.addProperty("rows", "10");
        body.addProperty("page", "1");

        publicApi.jpylCheckUserCompleteInfo(userID, body.toString()).map(new Func1<ResponseModel<CompleteModel>, CompleteModel>() {
            @Override
            public CompleteModel call(ResponseModel<CompleteModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<CompleteModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        } else {
                        }
                    }

                    @Override
                    public void onNext(CompleteModel object) {
                        if ("true".equals(object.getComplete())) {
                            startActivity(new Intent(getActivity(),
                                    DateOfCheckActivity.class).putExtra
                                    ("title", getList().get(position)).putExtra("pos",
                                    position));
                        } else {
                            ViewKit.showToast(getContext(), "完善用户信息后查看");

                        }


                    }
                });
    }

    /**
     * 添加测试数据
     *
     * @return
     */
    private List<String> getList() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            if (i == 0) {
                list.add("HPV检查");
            }
            if (i == 1) {
                list.add("HP检查");
            }
            if (i == 2) {
                list.add("Se检查");
            }
        }
        return list;
    }


    //获得广告
    void GetAds() {
        publicApi.jpylGetAds().map(new Func1<ResponseModel<RowsPeripheralModel>,
                RowsPeripheralModel>() {
            @Override
            public RowsPeripheralModel call(ResponseModel<RowsPeripheralModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RowsPeripheralModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
//                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        }
                    }

                    @Override
                    public void onNext(RowsPeripheralModel model) {
                        if (!JavaKit.isListEmpty(model.getRows())) {
                            rowsModelList = new ArrayList<>();
                            rowsModelList.addAll(model.getRows());
                            List<String> urlList = new ArrayList<>();
                            for (RowsModel rowsModel : rowsModelList) {
                                urlList.add(rowsModel.getPicurl());
                            }
                            StringUtil.setBannerStyle(bannerHome, urlList);
                        }
                    }
                });
    }

}
